#!/usr/bin/env python
"""
module that displays a TOD model for a given object_id
"""
from object_recognition_tod import ecto_detection
from ecto_image_pipeline.conversion import MatToPointCloudXYZ
from object_recognition_core.db import tools as dbtools, models
from object_recognition_core.utils.parser import ObjectRecognitionParser
import couchdb
import ecto
import ecto_pcl

if __name__ == '__main__':
    parser = ObjectRecognitionParser()
    dbtools.add_db_arguments(parser)
    parser.add_argument('object_id', help='The id of the object for which the TOD model will be displayed.')
    from ecto.opts import scheduler_options, run_plasm
    # disabled as scheduler tuning is useless for that application
    scheduler_options(parser)

    # read the object_ids
    args = parser.parse_args()
    object_id = args.object_id

    #database ritual
    db_url = args.db_root
    couch = couchdb.Server(db_url)
    dbs = dbtools.init_object_databases(couch)

    tod_models = models.find_model_for_object(dbs, object_id, 'TOD')

    if len(tod_models) < 1:
        raise RuntimeError("There are no tod models available.")

    db_reader = ecto_detection.ModelReader('db_reader', db_params=dbtools.args_to_db_params(args))
    #observation dealer will deal out each observation id.
    observation_dealer = ecto.Dealer(tendril=db_reader.inputs.at('model_id'), iterable=tod_models)
    to_pcl = MatToPointCloudXYZ()
    pcl_cloud = ecto_pcl.PointCloudT2PointCloud(format=ecto_pcl.Format.XYZ)
    cloud_viewer = ecto_pcl.CloudViewer()
    plasm = ecto.Plasm()
    #View all of the observations.
    plasm.connect(
        observation_dealer[:] >> db_reader['model_id'],
        db_reader['points'] >> to_pcl['points'],
        to_pcl['point_cloud'] >> pcl_cloud[:],
        pcl_cloud[:] >> cloud_viewer[:]
    )

    run_plasm(args, plasm)
#    doit(plasm, "View observations from the database.", locals=vars())
    
    raw_input()
